import { AutorotatePlugin } from "@photo-sphere-viewer/autorotate-plugin";
import React, { useCallback, useRef, useState, useEffect } from "react";
import { ReactPhotoSphereViewer } from "react-photo-sphere-viewer";

type Props = {
  src: string;
  height?: string;
  width?: string;
  // 在用户第一次与全景交互时调用（例如点击/拖拽）
  onStartInteraction?: () => void;
};

const PhotoSphere: React.FC<Props> = ({
  src,
  height = "100%",
  width = "100%",
  onStartInteraction,
}) => {
  const viewerRef = useRef<any>(null);
  const [isInit, setIsInit] = useState(true);
  // 本地交互标记，防止重复触发父级回调
  const [hasInteracted, setHasInteracted] = useState(false);
  const timeoutRef = useRef<number | null>(null);

  // 动画参数配置
  const animatedValues = {
    pitch: { start: -Math.PI / 2, end: 0 },
    yaw: { start: Math.PI / 2, end: 0 },
    zoom: { start: 0, end: 50 },
    maxFov: { start: 130, end: 90 },
    fisheye: { start: 2, end: 0 },
  };

  // 执行入场动画
  const intro = useCallback((targetPitch: number, targetYaw: number) => {
    if (!viewerRef.current) return;

    setIsInit(false);
    const viewer = viewerRef.current;

    // 禁用交互
    viewer.setOptions({
      mousemove: false,
      mousewheel: false,
    });

    const duration = 2500;
    const startTime = Date.now();

    const animateFrame = () => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / duration, 1);
      
      // easeInOutQuad 缓动
      const eased = progress < 0.5 
        ? 2 * progress * progress 
        : 1 - Math.pow(-2 * progress + 2, 2) / 2;

      // 计算当前值
      const currentPitch = animatedValues.pitch.start + (targetPitch - animatedValues.pitch.start) * eased;
      const currentYaw = animatedValues.yaw.start + (targetYaw - animatedValues.yaw.start) * eased;
      const currentZoom = animatedValues.zoom.start + (animatedValues.zoom.end - animatedValues.zoom.start) * eased;
      const currentMaxFov = animatedValues.maxFov.start + (animatedValues.maxFov.end - animatedValues.maxFov.start) * eased;
      const currentFisheye = animatedValues.fisheye.start + (animatedValues.fisheye.end - animatedValues.fisheye.start) * eased;

      // 应用值
      try {
        viewer.setOptions({
          fisheye: currentFisheye,
          maxFov: currentMaxFov,
        });
        viewer.rotate({ yaw: currentYaw, pitch: currentPitch });
        viewer.zoom(currentZoom);
      } catch (error) {
        console.log('动画更新失败:', error);
      }

      if (progress < 1) {
        requestAnimationFrame(animateFrame);
      } else {
        // 动画完成，启用交互
        viewer.setOptions({
          mousemove: true,
          mousewheel: true,
        });
      }
    };

    requestAnimationFrame(animateFrame);
  }, [animatedValues]);

  const handleReady = useCallback((instance: any) => {
    viewerRef.current = instance;

    // 清除之前的定时器
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    // 设置初始状态为星球视角
    instance.setOptions({
      fisheye: animatedValues.fisheye.start,
      maxFov: animatedValues.maxFov.start,
      mousemove: false,
      mousewheel: false,
    });

    instance.rotate({ 
      yaw: animatedValues.yaw.start, 
      pitch: animatedValues.pitch.start 
    });
    instance.zoom(animatedValues.zoom.start);

    // 只有在初始状态时才设置自动动画定时器 - 改为3秒
    if (isInit) {
      timeoutRef.current = window.setTimeout(() => {
        if (isInit && viewerRef.current) {
          intro(animatedValues.pitch.end, animatedValues.yaw.end);
        }
      }, 1000);
    }
  }, [intro, isInit, animatedValues]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  return (
    <div
      style={{ width, height, position: 'relative' }}
      onPointerDown={() => {
        if (!hasInteracted) {
          setHasInteracted(true);
          try {
            onStartInteraction && onStartInteraction();
          } catch (e) {
            // ignore
          }
        }
      }}
    >
  <ReactPhotoSphereViewer
        src={src}
        height={height}
        width={width}
        onReady={handleReady}
        navbar={false}
        defaultPitch={animatedValues.pitch.start}
        defaultYaw={animatedValues.yaw.start}
        defaultZoomLvl={animatedValues.zoom.start}
        loadingTxt={"加载中"}
       // loadingImg={"/loading.gif"}
        ref={viewerRef}
        // 初始状态禁用交互
        mousemove={!isInit}
        // 初始状态禁用交互
        mousewheelCtrlKey={false}
        touchmoveTwoFingers={false}
        plugins={[[AutorotatePlugin, { 
          autostartDelay: 5000, // 不自动启动，由我们控制
          autorotateSpeed: '1rpm', // 设置较慢的旋转速度，默认是2rpm
          autorotatePitch:null
        }]]}
      />
    </div>
  );
};

export default PhotoSphere;
